package com.ipan.poi.orm;

import com.ipan.poi.utils.PoiStringHelper;

/**
 * 实体类到数据库表的命名策略实现；
 * java名与表名对应是将驼峰结构改成下划线的策略的结构；
 * 跟Hibernate的ImprovedNamingStrategy类似；
 * 
 * @author iPan
 * @version 2013-9-21
 */
public class DefaultNamingStrategy implements NamingStrategy {

	public String classToTableName(String className) {
		return addUnderscores(PoiStringHelper.unqualify(className));
	}

	public String propertyToColumnName(String propertyName) {
		return addUnderscores(PoiStringHelper.unqualify(propertyName));
	}

	protected static String addUnderscores(String name) {
		StringBuffer buf = new StringBuffer(name.replace('.', '_'));
		for (int i = 1; i < buf.length() - 1; i++) {
			if (Character.isLowerCase(buf.charAt(i - 1)) && Character.isUpperCase(buf.charAt(i))
					&& Character.isLowerCase(buf.charAt(i + 1))) {
				buf.insert(i++, '_');
			}
		}
		return buf.toString().toLowerCase();
	}
}
